package runesim.friendserver;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;

public class FriendServerConnection implements IConnectHandler, IDataHandler, IDisconnectHandler {
	
	// @Override
	public boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
		System.out.println("Node connecting");
		Node n = new Node(-1, connection);
		n.setState(Node.STATE_NEW);
		connection.setAttachment(n);
		return false;
	}
	
	// @Override
	public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
		Node n = (Node) connection.getAttachment();
		
		if(n.getState() == Node.STATE_NEW) { // Needs authorization etc
			int id = connection.readByte();
			n.setID(id);
			n.setState(Node.STATE_OK);
			System.out.println("Node ready");
		} else if(n.getState() == Node.STATE_OK) { // Ready to receive/send
			// packets
			// TODO impl packet protocol
		}
		return false;
	}
	
	// @Override
	public boolean onDisconnect(INonBlockingConnection connection) throws IOException {
		System.out.println("Node disconnecting");
		return false;
	}
	
}
